import os
from PIL import Image

import mimetypes

from damn.transcoder import TranscoderFailedException, BaseTranscoder


class ImageTranscoder(BaseTranscoder):
  transcoder = True
  convert_map = {"image/jpeg" : ["image/jpeg", "image/png"], 
                 "image/png" : ["image/jpeg", "image/png"], 
                 "image/tga" : ["image/jpeg", "image/png"],
                 "image/gif" : ["image/jpeg", "image/png"],
                 "image/tiff" : ["image/jpeg", "image/png"],}
  _options = [('sizex', int, None), ('sizey', int, None),]
  options_map = {"image/jpeg" : _options, 
                 "image/png" : _options, 
                 "image/tga" : _options,
                 "image/gif" : _options,
                 "image/tiff" : _options,}

  def transcode(self, anAssetReference, dstFormat, **kwargs): 
    filePath = super(ImageTranscoder, self).transcode(anAssetReference, dstFormat, kwargs)
     
    try:  
      im = Image.open(anAssetReference.file.fileName)
    except IOError:
      print "cannot open", anAssetReference.file.fileName
      return False

    size, differ = self.normalize_size(kwargs, im)   
    if differ:
      im.thumbnail((size[0], size[1]))
    
    if im.mode == 'P':
      im = im.convert('RGB')
      
    im.save(filePath)
    
    return filePath
